#!/usr/bin/python3
# _*_ coding:utf-8 _*_
# __author__ = '__Csm__'


from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DeleteView
from django.template.loader import render_to_string
from django.http.response import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.urls import reverse_lazy

from zanhu.news.models import News
from zanhu.helpers import ajax_required, AuthorRequireMixin


class NewsListView(LoginRequiredMixin, ListView):
    """首页动态"""
    model = News
    paginate_by = 20  # url中的page=
    template_name = 'news/news_list.html'  # 默认是模型类名_list.html

    def get_queryset(self):
        return News.objects.filter(reply=False)


class NewsDeleteView(LoginRequiredMixin, AuthorRequireMixin, DeleteView):
    model = News
    template_name = 'news/news_confirm_delete.html'
    # slug_url_kwarg = 'slug'  #通过url传入要删除的对象主键id，默认值是slug
    # pk_url_kwarg = 'pk'  #通过url传入要删除的对象主键id，默认值是pk
    success_url = reverse_lazy("news:list")


@login_required
@ajax_required
@require_http_methods(['POST'])
def post_new(request):
    """发送动态AJAX POST请求"""
    post = request.POST['post'].strip()
    print(post)
    if post:
        posted = News.objects.create(user=request.user, content=post)
        html = render_to_string('news/news_single.html', {'news': posted, 'request': request})
        #  使用render_to_string需要将request加到上下文内
        return HttpResponse(html)
    else:
        return HttpResponseBadRequest("内容不能为空")


@login_required
@ajax_required
@require_http_methods(['POST'])
def like(request):
    news_id = request.POST['news']
    news = News.objects.get(pk=news_id)
    # 取消赞或者添加赞
    news.switch_like(request.user)
    return JsonResponse({'likes': news.count_likers()})


@login_required
@ajax_required
@require_http_methods(['GET'])
def get_thread(request):
    """返回动态评论，AJAX GET 请求"""
    news_id = request.GET['news']
    news = News.objects.get(pk=news_id)
    news_html = render_to_string('news/news_single.html', {'news': news})  #没有评论显示的页面
    thread_html = render_to_string('news/news_thread.html', {'thread': news.get_thread()})  #有评论显示的页面
    return JsonResponse({
        'uuid': news_id,
        'news': news_html,
        'thread': thread_html
    })


@login_required
@ajax_required
@require_http_methods(['POST'])
def post_comment(request):
    """评论，AJAX post请求"""
    post = request.POST['reply'].strip()
    parent_id = request.POST['parent']
    parent = News.objects.get(pk=parent_id)
    if post:
        parent.reply_this(request.user, post)
        return JsonResponse({'comments':parent.comment_count()})
    else:
        return HttpResponseBadRequest("内容不能为空")


@login_required
@ajax_required
@require_http_methods(["POST"])
def update_interactions(request):
    """更新互动信息"""
    data_point = request.POST['id_value']
    news = News.objects.get(pk=data_point)
    return JsonResponse({'likes': news.count_likers(), 'comments': news.comment_count()})
